package com.example.administrator.basedemos.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.basedemos.R;
import com.example.administrator.basedemos.adapter.MultiThanAdapter;
import com.example.administrator.basedemos.adapter.RecommendFragmentAdapter;
import com.example.administrator.basedemos.bean.MutliSearchBean;
import com.example.administrator.basedemos.utils.RecycleUtil;
import com.example.administrator.basedemos.view.MyMarkerView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

import static com.github.mikephil.charting.components.XAxis.XAxisPosition.BOTTOM;

/**
 * 创建者     ZCL
 * 创建时间   2018/7/26 10:36
 * 描述	      {币交易所详情}
 * <p>
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   TODO
 */
public class ThanExchangeActivity extends BaseZcActivity implements OnChartValueSelectedListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.z_than_toolbar_title)
    TextView                                      mZToolbarTitle;
    @BindView(R.id.z_than_ex_icon)
    ImageView                                     mZThanExIcon;
    @BindView(R.id.z_than_ex_name)
    TextView                                      mZThanExName;
    @BindView(R.id.chart1)
    LineChart                                     mChart;
    @BindView(R.id.market_rank_l)
    TextView                                      mMarketRankL;
    @BindView(R.id.market_rank_m)
    TextView                                      mMarketRankM;
    @BindView(R.id.market_rank_r)
    TextView                                      mMarketRankR;
    @BindView(R.id.recyclerview_mw)
    RecyclerView                                  mRecyclerviewMw;
    @BindView(R.id.recyclerview_mm)
    RecyclerView                                  mRecyclerviewMm;
    @BindView(R.id.z_than_load_all)
    LinearLayout                                  mZThanLoadAll;
    @BindView(R.id.shriank_textview)
    com.ytt.bargraph.huaweipaydemo.MyLinearLayout mShriankTextview;
    private Typeface                 mTfLight;
    private RecommendFragmentAdapter mAdapter;
    private ArrayList<String>        mList;
    private Drawable                 mDrawableL;
    private Drawable                 mDrawableM;
    private Drawable                 mDrawableR;
    private boolean                  mRankNumLDown;
    private boolean                  mRankNumMDown;
    private boolean                  mRankNumRDown;
    private MultiThanAdapter         mMultiThanAdapter;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_than_excahnge;
    }

    @Override
    protected void initData() {
        mZThanLoadAll.setVisibility(View.VISIBLE);
        mToolbarLy.setVisibility(View.GONE);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            String title = bundle.getString("title");
            mZToolbarTitle.setText(title);
            Toast.makeText(getApplicationContext(), title, Toast.LENGTH_SHORT).show();
        }
        mTfLight = Typeface.createFromAsset(getAssets(), "OpenSans-Light.ttf");
        setcharData();

        mRankNumLDown = true;
        mRankNumMDown = true;
        mRankNumRDown = true;

        mShriankTextview.setText("当初看到这个需求的时候，还以为十分简单，但是做起来之后，虽然可以实现" +
                "textview的展开与收缩，但是，指示箭头却不能轻易的去控制。因为TextView的数据从服务端获取的，" +
                "我们并不知道服务端给的一个字符串是占用1行还是2行还是多行，所以这个箭头就不好控制了。后面想到测" +
                "量TextView的高度，但是当TextView 设置了maxline的属性之后，并不能拿到实际高度了。思考了好久之后，" +
                "终于想到一个办法，再借用一个TextView, 不设置任何属性，测量它的高度。然后将拿到的高度和设置了" +
                "maxline的TextView的高度进行比较。借用的TextView的高度大的话，说明，服务端给的数据超过2行，" +
                "这时，我们让指示箭头展示，否则，就隐藏指示箭头。", 3, true);

        mList = new ArrayList<>();
        mList.add("xx");
        mList.add("22xx2");
        mList.add("xxx");
        mList.add("xxxu");

        ArrayList<MutliSearchBean> list = new ArrayList<>();
        list.add(new MutliSearchBean(0));
        list.add(new MutliSearchBean(1));
        list.add(new MutliSearchBean(1));
        list.add(new MutliSearchBean(0));

        RecycleUtil.setLayoutMangerVertical(mRecyclerviewMw, this);
        RecycleUtil.setLayoutMangerVertical(mRecyclerviewMm, this);

        mAdapter = new RecommendFragmentAdapter(R.layout.item_recomend, mList);
        mMultiThanAdapter = new MultiThanAdapter(list);

        mRecyclerviewMw.setAdapter(mAdapter);
        mRecyclerviewMm.setAdapter(mMultiThanAdapter);
        //必须添加getparent否则不显示

        //Item子控件的点击事件
        //首先在adapter的convert方法里面通过viewHolder.addOnClickListener绑定一下的控件id
        mMultiThanAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemClickListener(this);
    }

    private void setcharData() {
        ArrayList<Entry> yVals = new ArrayList<Entry>();
        int range = 100;
        for (int i = 0; i < 10; i++) {
            float mult = (range + 1);
            float val = (float) (Math.random() * mult) + 20;// 101以内的随机数家20 也就是20-120
            Log.i("xxx", "val:" + val + "----x:" + i);
            yVals.add(new Entry(i, val));
        }

        LineDataSet set1;

        //设置chart是否可以触摸
        mChart.setTouchEnabled(true);
        //设置是否可以拖拽  
        mChart.setDragEnabled(false);
        //设置是否可以缩放 x和y，默认true  
        mChart.setScaleEnabled(false);
        mChart.setDrawGridBackground(false);//不绘制网格线
        mChart.setExtraBottomOffset(10);  //距离底部的padding
        mChart.setPinchZoom(true);
        //去除描述
        mChart.getDescription().setEnabled(false);
        mChart.setOnChartValueSelectedListener(this);
        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);//弹框提示
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart

        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();

        // modify the legend ...
        l.setForm(Legend.LegendForm.LINE);
        l.setTypeface(mTfLight);
        l.setTextSize(11f);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        l.setEnabled(false);  //去除底部标签描述

        XAxis xAxis = mChart.getXAxis();
        xAxis.setTypeface(mTfLight);
        xAxis.setTextSize(11f);
        xAxis.setTextColor(Color.parseColor("#7F8C8D"));
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMinimum(1f);
        xAxis.setPosition(BOTTOM);
        xAxis.setEnabled(true);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTypeface(mTfLight);
        leftAxis.setTextColor(this.getResources().getColor(R.color.gray_d));//Color.parseColor("#7F8C8D")
        leftAxis.enableGridDashedLine(0f, 55f, 0);
        leftAxis.setGridColor(/*Color.parseColor("#E0E0E0")*/this.getResources().getColor(R.color.gray_d));
        leftAxis.setAxisMinimum(0f);
        leftAxis.setDrawGridLines(true);

        YAxis rightAxis = mChart.getAxisRight();
        YAxis lefttAxis = mChart.getAxisLeft();
        rightAxis.setEnabled(false);//右侧Y轴不可见
        lefttAxis.setEnabled(true);//左侧Y轴不可见

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals, "label");
            set1.setMode(LineDataSet.Mode.CUBIC_BEZIER);
            // 行云需求趋势图
            set1.setColor(Color.YELLOW);
            set1.setDrawCircles(false);
            set1.setDrawCircleHole(false);
            set1.setLineWidth(1f);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);
            set1.setFormLineWidth(1f);
            set1.setFormLineDashEffect(new DashPathEffect(new float[]{10f, 5f}, 0f));
            set1.setFormSize(15.f);


            set1.setFillFormatter(new IFillFormatter() {
                @Override
                public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                    return -10;
                }
            });


            //设置颜色
            if (Utils.getSDKInt() >= 18) {
                // fill drawable only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
                set1.setFillDrawable(drawable);
            } else {
                set1.setFillColor(Color.BLACK);
            }

            // create a data object with the datasets
            LineData data = new LineData(set1);
            data.setValueTypeface(mTfLight);
            data.setValueTextSize(9f);
            data.setDrawValues(false);

            // set data
            mChart.setData(data);
        }
    }

    @OnClick({R.id.z_than_toolbar_add, R.id.z_than_toolbar_share, R.id.z_than_toolbar, R.id.market_rank_l,
            R.id.market_rank_m, R.id.market_rank_r, R.id.z_than_load_all})
    public void OnClik(View v) {

        if (v.getId() == R.id.market_rank_r || v.getId() == R.id.market_rank_m || v.getId() == R.id.market_rank_l) {
            mDrawableL = null;
            mDrawableM = null;
            mDrawableR = null;
        }
        switch (v.getId()) {
            case R.id.z_than_toolbar:
                finish();
                break;
            case R.id.z_than_toolbar_add:
                Intent intent = new Intent(this, OptionalAddActivity.class);
                startActivity(intent);
                break;
            case R.id.z_than_toolbar_share:
                // Intent intent = new Intent(this, .class);
                //startActivity(intent);
                break;

            case R.id.market_rank_l:
                setArrowChoice(mDrawableL, mRankNumLDown, 0);
                break;
            case R.id.market_rank_m:
                setArrowChoice(mDrawableM, mRankNumMDown, 1);
                break;
            case R.id.market_rank_r:
                setArrowChoice(mDrawableR, mRankNumRDown, 2);
                break;
            case R.id.z_than_load_all:
                mList.add("haha");
                mList.add("ha1");
                mList.add("ha2");
                mList.add("ha3");
                mAdapter.notifyDataSetChanged();
                mZThanLoadAll.setVisibility(View.GONE);
                break;
        }
    }


    private void setArrowChoice(Drawable draw, boolean mRankNum, int type) {
        mRankNum = mRankNum ? false : true;
        if (mRankNum) {
            if (type == 0)
                draw = getResources().getDrawable(R.mipmap.down_b_arrow);
            else
                draw = getResources().getDrawable(R.mipmap.down_g_arrow);
        } else
            draw = getResources().getDrawable(R.mipmap.up_b_arrow);

        draw.setBounds(0, 0, draw.getMinimumWidth(), draw.getMinimumHeight());


        switch (type) {
            case 0:
                mRankNumLDown = mRankNum;
                mMarketRankL.setCompoundDrawables(null, null, draw, null);
                break;
            case 1:
                mRankNumMDown = mRankNum;
                mMarketRankM.setCompoundDrawables(null, null, draw, null);
                break;
            case 2:
                mRankNumRDown = mRankNum;
                mMarketRankR.setCompoundDrawables(null, null, draw, null);
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(this, ThanExchangeActivity.class);
        Bundle bundle = new Bundle();
        bundle = setBundle(bundle, position);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private Bundle setBundle(Bundle bundle, int position) {
        bundle.putString("title", mList.get(position));
        return bundle;
    }


    @Override
    public void initListener() {
        super.initListener();
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

    }
}